<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">设备统计</h2>
      <div class="flex space-x-3">
        <select v-model="selectedPeriod" @change="loadStatistics" class="px-3 py-2 border border-gray-300 rounded-md shadow-sm text-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
          <option value="week">本周</option>
          <option value="month">本月</option>
          <option value="quarter">本季度</option>
          <option value="year">本年</option>
        </select>
        <button @click="exportStatistics" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
          <DocumentArrowDownIcon class="h-5 w-5 mr-2" />
          导出统计
        </button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-blue-500 to-blue-600">
          <ChartBarIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.totalEquipment }}</div>
          <div class="text-sm text-gray-500">设备总数</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-green-500 to-green-600">
          <CheckCircleIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.normalEquipment }}</div>
          <div class="text-sm text-gray-500">正常设备</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-yellow-500 to-yellow-600">
          <HandRaisedIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.borrowedEquipment }}</div>
          <div class="text-sm text-gray-500">借用中设备</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-red-500 to-red-600">
          <WrenchScrewdriverIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.repairingEquipment }}</div>
          <div class="text-sm text-gray-500">维修中设备</div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- 设备状态分布饼图 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">设备状态分布</h3>
        <div class="h-80">
          <v-chart 
            class="w-full h-full" 
            :option="statusPieOption" 
            autoresize
          />
        </div>
      </div>

      <!-- 设备类别分布柱状图 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">设备类别分布</h3>
        <div class="h-80">
          <v-chart 
            class="w-full h-full" 
            :option="categoryBarOption" 
            autoresize
          />
        </div>
      </div>
    </div>

    <!-- 使用趋势图 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">设备使用趋势</h3>
      <div class="h-80">
        <v-chart 
          class="w-full h-full" 
          :option="trendLineOption" 
          autoresize
        />
      </div>
    </div>

    <!-- 实验室设备分布 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">各实验室设备分布</h3>
      <div class="h-80">
        <v-chart 
          class="w-full h-full" 
          :option="laboratoryRadarOption" 
          autoresize
        />
      </div>
    </div>

    <!-- 设备使用趋势表格 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">设备使用趋势</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">月份</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备申请数</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备借用数</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备使用率</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="(month, index) in usageTrendData.months" :key="month">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ month }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ usageTrendData.applicationCounts[index] || 0 }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ usageTrendData.borrowCounts[index] || 0 }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ (usageTrendData.usageRates[index] || 0).toFixed(1) }}%</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 设备类别统计表格 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">设备类别统计</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备类别</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备数量</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总价值</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">平均价值</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="stat in detailedStats" :key="stat.category">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ stat.category }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ stat.count }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ stat.totalValue?.toLocaleString() || 0 }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ stat.totalValue ? (stat.totalValue / stat.count).toLocaleString() : 0 }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, LineChart, RadarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent
} from 'echarts/components'
import * as echarts from 'echarts'
import VChart from 'vue-echarts'
import {
  ChartBarIcon,
  CheckCircleIcon,
  HandRaisedIcon,
  WrenchScrewdriverIcon,
  DocumentArrowDownIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  RadarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent
])

const selectedPeriod = ref('month')
const loading = ref(false)

const statistics = reactive({
  totalEquipment: 0,
  normalEquipment: 0,
  borrowedEquipment: 0,
  repairingEquipment: 0,
  scrappedEquipment: 0
})

const detailedStats = ref([])
const laboratoryStats = ref([])
const usageTrendData = ref({
  months: [],
  applicationCounts: [],
  borrowCounts: [],
  usageRates: []
})

// 设备状态分布饼图配置
const statusPieOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['正常', '借用中', '维修中', '已报废']
  },
  series: [
    {
      name: '设备状态',
      type: 'pie',
      radius: '50%',
      center: ['50%', '50%'],
      data: [
        { value: statistics.normalEquipment, name: '正常', itemStyle: { color: '#10B981' } },
        { value: statistics.borrowedEquipment, name: '借用中', itemStyle: { color: '#F59E0B' } },
        { value: statistics.repairingEquipment, name: '维修中', itemStyle: { color: '#EF4444' } },
        { value: statistics.scrappedEquipment, name: '已报废', itemStyle: { color: '#6B7280' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 设备类别分布柱状图配置
const categoryBarOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: detailedStats.value.map(item => item.category),
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '设备数量',
      type: 'bar',
      data: detailedStats.value.map(item => item.count),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#3B82F6' },
          { offset: 1, color: '#1D4ED8' }
        ])
      }
    }
  ]
}))

// 使用趋势线图配置
const trendLineOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['设备申请数', '设备借用数', '设备使用率']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: usageTrendData.value.months || ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: [
    {
      type: 'value',
      name: '数量',
      axisLabel: {
        formatter: '{value}'
      }
    },
    {
      type: 'value',
      name: '使用率(%)',
      axisLabel: {
        formatter: '{value}%'
      }
    }
  ],
  series: [
    {
      name: '设备申请数',
      type: 'line',
      data: usageTrendData.value.applicationCounts || [],
      smooth: true,
      itemStyle: { color: '#3B82F6' }
    },
    {
      name: '设备借用数',
      type: 'line',
      data: usageTrendData.value.borrowCounts || [],
      smooth: true,
      itemStyle: { color: '#F59E0B' }
    },
    {
      name: '设备使用率',
      type: 'line',
      data: usageTrendData.value.usageRates || [],
      smooth: true,
      itemStyle: { color: '#10B981' },
      yAxisIndex: 1
    }
  ]
}))

// 实验室设备分布雷达图配置
const laboratoryRadarOption = computed(() => {
  if (!laboratoryStats.value || laboratoryStats.value.length === 0) {
    return {
      tooltip: {},
      legend: {
        data: ['设备数量']
      },
      radar: {
        indicator: []
      },
      series: [
        {
          name: '实验室设备分布',
          type: 'radar',
          data: []
        }
      ]
    }
  }
  
  const maxCount = Math.max(...laboratoryStats.value.map(stat => stat.count), 1)
  
  return {
    tooltip: {},
    legend: {
      data: ['设备数量']
    },
    radar: {
      indicator: laboratoryStats.value.map(stat => ({
        name: stat.laboratoryName,
        max: Math.max(maxCount, 10)
      }))
    },
    series: [
      {
        name: '实验室设备分布',
        type: 'radar',
        data: [
          {
            value: laboratoryStats.value.map(stat => stat.count),
            name: '设备数量',
            itemStyle: { color: '#3B82F6' }
          }
        ]
      }
    ]
  }
})

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true
    
    // 加载基础统计数据
    const response = await request.get('/statistics/equipment')
    Object.assign(statistics, response.data)
    
    // 使用后端返回的类别统计数据
    if (response.data.categoryStatistics) {
      detailedStats.value = response.data.categoryStatistics.map(item => ({
        category: item.category,
        count: item.count,
        total: item.count, // 为了兼容现有代码
        totalValue: item.totalValue,
        normal: 0, // 这些字段需要从其他API获取
        borrowed: 0,
        repairing: 0,
        scrapped: 0,
        usageRate: 0
      }))
    }
    
    // 使用后端返回的实验室统计数据
    if (response.data.laboratoryStatistics) {
      laboratoryStats.value = response.data.laboratoryStatistics.map(item => ({
        laboratoryName: item.laboratoryName,
        count: item.count,
        totalValue: item.totalValue
      }))
    }
    
    // 加载使用趋势数据
    const trendResponse = await request.get('/statistics/equipment/trend')
    if (trendResponse.data) {
      usageTrendData.value = {
        months: trendResponse.data.months || [],
        applicationCounts: trendResponse.data.applicationCounts || [],
        borrowCounts: trendResponse.data.borrowCounts || [],
        usageRates: trendResponse.data.usageRates || []
      }
    }
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
    showMessage('加载统计数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 导出统计
const exportStatistics = async () => {
  try {
    // 调用后端API导出统计报告
    const response = await request.get('/reports/equipment/export', {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `设备统计报告_${new Date().toISOString().split('T')[0]}.xlsx`
    document.body.appendChild(link)
    link.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(link)
    
    showMessage('统计报告导出成功', 'success')
  } catch (error) {
    console.error('导出统计失败:', error)
    showMessage('导出统计失败', 'error')
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadStatistics()
})
</script>